package com.wsh.generator.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsh.entity.generator.TableColumnInfoEntity;
import com.wsh.enums.BadStatusEnum;
import com.wsh.exception.BadRequestException;
import com.wsh.generator.TableColumnInfoService;
import com.wsh.mapper.generator.TableColumnInfoDao;
import com.wsh.utils.StringUtils;
import com.wsh.vo.generator.TableColumnInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class TableColumnInfoServiceImpl extends ServiceImpl<TableColumnInfoDao, TableColumnInfoEntity> implements TableColumnInfoService {
    @Autowired
    private TableColumnInfoDao tableColumnInfoDao;

    /**
     * 更新表信息
     *
     * @param dto
     * @return
     */
    @Override
    public void updateTableColumnInfo(TableColumnInfoVo dto) throws Exception {
        String[] types = {"bigint", "smallint", "tinyint", "year", "tinyblob","datetime","longtext","blob","date","enum","longblob","mediumblob","mediumtext","multilinestring","multipoint","text","time","timestamp","tinytext"};
        List<String> typeList = Arrays.asList(types);

        // 查询表中是否有数据，如果有数据，不允许操作表
        String tableName;
        boolean isExit = (this.queryCountTable((tableName = dto.getTableName()))) > 0;
        if (isExit) {
            throw new BadRequestException(BadStatusEnum.TABLE_BAD_EXIST_DATA.getMsg());
        }
        if (StringUtils.isBlank(tableName)) {
            throw new BadRequestException(BadStatusEnum.TABLE_ALTER_BAD_TABLENAMENULL.getMsg());
        }

        // 保存字段集合
        List<TableColumnInfoEntity> addColumnList = new ArrayList<>();

        for (TableColumnInfoEntity info : dto.getTableInfoList()) {
            TableColumnInfoEntity entity = new TableColumnInfoEntity();
            String columnNames = info.getCName();
            String columnType = info.getCType();
            String columnLength = info.getCLength();
            String columnComment = info.getCComment();
            entity.setTableName(tableName);
            // 定义字段名称
            String[] cNames;
            // 无逗号分隔则为增加字段
            if ((cNames = columnNames.split(",")).length == 1) {
                entity.setCName(columnNames);
                entity.setCType(columnType);
                if (!typeList.contains(columnType)) {
                    entity.setCLength(columnLength);
                }
                entity.setCComment(columnComment);
                addColumnList.add(entity);
                continue;
            }
            if (cNames.length != 2) {
                throw new BadRequestException(BadStatusEnum.TABLE_BAD_COLUMNLENGTH.getMsg());
            }
            // 定义原字段名称
            String oName;
            // 定义保存字段名称
            String cName;
            if (StringUtils.isBlank(oName = cNames[0]) || StringUtils.isBlank(cName = cNames[1])) {
                throw new BadRequestException(BadStatusEnum.TABLE_BAD_COLUMNNAME.getMsg());
            }
            entity.setOName(oName);
            entity.setCName(cName);

            if (StringUtils.isNotBlank(columnType) && StringUtils.isNotBlank(columnLength)) {
                entity.setCType(columnType);
                if (!typeList.contains(columnType)) {
                    entity.setCLength(columnLength);
                }
                this.updateColumn(entity);
                // 不修改长度
            } else if (StringUtils.isNotBlank(columnType) && StringUtils.isBlank(columnLength)) {
                // 查询原来长度
                if (!typeList.contains(columnType)) {
                    entity.setCLength(tableColumnInfoDao.queryColumnLength(entity));
                }
                entity.setCType(columnType);
                this.updateColumn(entity);
                // 不修改类型
            } else if (StringUtils.isNotBlank(columnLength) && StringUtils.isBlank(columnType)) {
                // 查询原来类型
                String type = tableColumnInfoDao.queryColumnType(entity);
                if (!typeList.contains(type)) {
                    entity.setCLength(columnLength);
                }
                entity.setCType(type);
                this.updateColumn(entity);
            } else if (!cName.equals(oName)) {
                String type = tableColumnInfoDao.queryColumnType(entity);
                if (!typeList.contains(type)) {
                    String length = tableColumnInfoDao.queryColumnLength(entity);
                    entity.setCLength(length);
                }
                entity.setCType(type);
                this.updateColumn(entity);
            }
            // 修改备注
            if (StringUtils.isNotBlank(columnComment)) {
                entity.setCComment(columnComment);
                updateColumnComment(entity);
            }
        }
        tableColumnInfoDao.addTableColumn(addColumnList, tableName);
    }


    /**
     * 修改字段备注
     *
     * @param entity
     */
    private void updateColumnComment(TableColumnInfoEntity entity) {
        try {
            tableColumnInfoDao.updateColumnComment(entity);
        } catch (Exception e) {
            log.error(this.getClass().getName() + ".updateColumnComment Exception={}", e.getMessage());
            throw new BadRequestException(BadStatusEnum.TABLE_ALTER_BAD_COLUMNCOMMENT.getMsg());
        }
    }

    /**
     * 修改字段名称
     *
     * @param entity
     */
    private void updateColumn(TableColumnInfoEntity entity) {
        try {
            tableColumnInfoDao.updateColumnName(entity);
        } catch (Exception e) {
            log.error(this.getClass().getName() + ".updateColumnName Exception={}", e.getMessage());
            throw new BadRequestException(BadStatusEnum.TABLE_ALTER_BAD_COLUMN.getMsg());
        }
    }

    /**
     * 根据表名查询表中的数据
     *
     * @param tableName
     * @return
     */
    private int queryCountTable(String tableName) {
        Integer integer = tableColumnInfoDao.queryCountTable(tableName);
        if (integer == null) {
            return 0;
        } else return integer.intValue();
    }


    public List<TableColumnInfoEntity> columnList(String tableName) {
       return tableColumnInfoDao.columnList(tableName);
    }
}
